<template>
  <div class="post-list-container">
    <h2 style="text-align: center; color: #333; margin-bottom: 20px;">校园墙 - 热门动态</h2>

    <el-card v-if="loading" class="post-card" shadow="never">
      <el-skeleton style="padding: 20px" :rows="6" animated />
    </el-card>

    <div v-else>
      <el-alert
        v-if="posts.length === 0"
        title="暂无内容"
        type="info"
        center
        show-icon
      />

      <el-card v-for="post in posts" :key="post.id" class="post-card" shadow="hover" style="margin-bottom: 16px"
      >
        <!-- 用户信息 -->
        <div class="post-header">
          <el-avatar :size="40" :src="getAvatar(post.userId)" />
          <div class="user-info">
            <div class="user-name">用户{{ post.userId }}</div>
            <div class="post-meta">
              {{ formatTime(post.createTime) }} · {{ post.location }}
            </div>
          </div>
        </div>

        <!-- 帖子内容 -->
        <div class="post-content">
          <p style="margin: 12px 0; line-height: 1.6;">{{ post.content }}</p>
        </div>

        <!-- 图片 -->
        <div v-if="post.images.length > 0" class="post-images">
          <el-image
            v-for="(img, idx) in post.images"
            :key="idx"
            :src="img"
            :alt="`图片${idx + 1}`"
            fit="cover"
            style="width: 100%; max-height: 300px; border-radius: 8px; margin-top: 8px;"
          />
        </div>

        <!-- 标签 -->
        <div v-if="post.tags.length > 0" class="post-tags">
          <el-tag
            v-for="(tag, idx) in post.tags"
            :key="idx"
            size="small"
            type="success"
            style="margin-right: 6px; margin-top: 6px"
          >
            {{ tag }}
          </el-tag>
        </div>

        <!-- 统计信息 -->
        <div class="post-stats">

          <button type="text" class="action-btn" :class="{ liked: isLiked }" @click="handleLike(post.id)">
            <i :class="isLiked ? 'fas fa-heart' : 'far fa-heart'"></i><span>{{ post.likeCount }}</span>
          </button>

          <button class="action-btn" @click="collect(post.id)">
              <i class="far fa-bookmark"></i>
              <span>收藏</span>
          </button>
          <!-- <el-button size="small" type="text" icon="View">{{ post.viewCount }}</el-button> -->
          <button class="action-btn" @click="toggleComments">
              <i class="far fa-comment"></i>
              <span>{{ post.commentCount }}</span>
          </button>
          <!-- <el-button size="small" type="text" icon="ChatLineRound">{{ post.commentCount }}</el-button> -->


          <button class="action-btn">
              <i class="fas fa-share-alt"></i>
              <span>分享</span>
          </button>
          <!-- <el-button size="small" type="text" icon="Share">{{ post.shareCount }}</el-button> -->

          <!-- 评论展开 -->
           <div v-if="isCommentsExpanded" class="comments-section">
              <div v-for="comment in post.comments" :key="comment.id" class="comment">
                  <img :src="comment.avatar" :alt="comment.author" class="comment-avatar">
                  <div class="comment-content">
                      <div class="comment-author">{{ comment.author }}</div>
                      <div class="comment-text">{{ comment.content }}</div>
                  </div>
              </div>
              <div class="add-comment">
                  <input v-model="commentText" type="text" class="comment-input" placeholder="写下你的评论...">
                  <button class="send-comment" @click="addComment">
                      <i class="fas fa-paper-plane"></i>
                  </button>
              </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getAllPosts,likePostApi, collectApi } from '@/api/home'


// 响应式数据
const posts = ref([]);
const loading = ref(true);

const commentText = ref('');
// -------------------------------------------------数据
const isLiked = ref(false);
const isCommentsExpanded = ref(false);

// ----------------------------------------------------


// ---------------------------------------------------方法
// 更改点赞状态
const toggleLike = () =>{
  isLiked.value = !isLiked.value;
}

// 点赞
const handleLike = async (id) =>{
  toggleLike();
  const res = await likePostApi(id);
  fetchPosts();
}

// 展开评论
const toggleComments = () => {
  isCommentsExpanded.value = !isCommentsExpanded.value;
};

// TODO 添加评论
const addComment = () => {
  if (commentText.value.trim()) {
      props.post.comments.push({
          id: Date.now(),
          author: '当前用户',
          avatar: 'https://ui-avatars.com/api/?name=用户&background=4e73df&color=fff',
          content: commentText.value,
          time: '刚刚'
      });
      commentText.value = '';
      props.post.commentsCount += 1;
  }
};

const isCollected = ref(false);

// 收藏或取消收藏
const collect = async (id) => {
  const result = await collectApi(id)
  if(result.value.code){// 收藏成功
    // 界面展示
    isCollected.value = !isCollected.value;
    fetchPosts();
  }else{// 提示
    console.log('收藏失败');
  }
}

// --------------------------------------------------



// 获取数据
const fetchPosts = async () => {
  try {
    const res = await getAllPosts()

    // ✅ 正确判断：检查返回的业务状态码
    if (res.data.code !== 1) {
      throw new Error(res.data.msg || '获取失败')
    }

    // ✅ 直接使用 res.data.data
    posts.value = res.data.data
      .filter(p => p.status === 1)
      .map(p => ({
        ...p,
        tags: JSON.parse(p.tags),
        images: JSON.parse(p.images)
      }))
  } catch (err) {
    console.error('获取帖子失败:', err)
    ElMessage?.error?.(err.message || '加载失败，请刷新重试')
  } finally {
    loading.value = false
  }
}

// 用户头像（根据 userId 生成不同头像，这里用占位图）
const getAvatar = (userId) => {
  return `https://picsum.photos/seed/user${userId}/200/200`
}

// 时间格式化（简化）
const formatTime = (isoString) => {
  return new Date(isoString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
/* ---------样式------------------------------------ */
.action-btn {
    display: flex;
    align-items: center;
    background: none;
    border: none;
    color: #858796;
    cursor: pointer;
    transition: color 0.2s;
    font-size: 0.9rem;
}

.action-btn:hover {
    color: var(--primary-color);
}

.action-btn i {
    margin-right: 5px;
}

.action-btn.liked {
    color: #e74a3b;
}

.comments-section {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid var(--light-gray);
}

.comment {
    display: flex;
    margin-bottom: 15px;
}

.comment-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    object-fit: cover;
}

.comment-content {
    flex: 1;
    background-color: #f8f9fc;
    padding: 10px 15px;
    border-radius: 18px;
}

.comment-author {
    font-weight: 700;
    font-size: 0.9rem;
    margin-bottom: 5px;
}

.comment-text {
    font-size: 0.9rem;
    color: #5a5c69;
}

.add-comment {
    display: flex;
    margin-top: 10px;
}

.comment-input {
    flex: 1;
    padding: 10px 15px;
    border: 1px solid var(--light-gray);
    border-radius: 20px;
    outline: none;
    font-size: 0.9rem;
}

.comment-input:focus {
    border-color: var(--primary-color);
}

.send-comment {
    margin-left: 10px;
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 50%;
    width: 38px;
    height: 38px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* --------------------------------------- */
.post-list-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
}

.post-card {
  border-radius: 12px;
  overflow: hidden;
  background-color: #ffffff;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  margin-left: 12px;
}

.user-name {
  font-weight: 600;
  color: #1f2d3d;
  font-size: 15px;
}

.post-meta {
  font-size: 13px;
  color: #999;
}

.post-content {
  font-size: 15px;
  color: #333;
}

.post-images {
  margin-top: 12px;
}

.post-tags {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
}

.post-stats {
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 16px;
}
</style>